
import FormValidators from 'Yan/utils/validators'
import request from '@/utils/request'
export default {
  inject: ['globalModel'],
  data() {
    return {
      pushFn: null
    }
  },
  computed: {
    fieldId() {
      return this.field.id
    },
    fieldLib() {
      return this.designer.fieldLib;
    },
    formModel: {
      cache: false,
      get() {
        return this.globalModel.formModel
      },
    },
    previewStatus() {
      return this.designer.previewStatus
    }
  },
  created() {
  },
  methods: {
    // --------------------- 组件内部方法 begin ------------------ //
    // 初始化表单单元的初始值
    initFieldModel() {
      if (this.field.type === 'table') this.fieldModel = this.formModel[this.fieldId] || [{}]
      else this.fieldModel = this.formModel[this.fieldId]
    },
    // 添加对应字段的监听事件
    initEventHandler() {
      if (this.previewStatus) return
      if (!(this.field.options.readonly || this.field.options.disabled)) return
      if (this.field.options.onListener) {
        // console.log('init listenerEvent =>', this.fieldId, this.field.options.readonly, this.field.options.disabled, this.field.options.onListener)
        // console.log('init listenerEvent =>', this.fieldId)
        // let listenerFu = new Function(this.field.options.onListener)

        const { onListener } = this.field.options
        let FunString = onListener
        FunString = FunString.replace(/(\$[^$]+\$)/g, (iStr) => {
          // console.log(iStr)
          let key = 'this.formData'
          if (iStr.indexOf('table_') === 1) key = 'this.formRow.row'
          return `${key}.${iStr.slice(1, -1).split('%')[0]}`
          // return iStr.slice(1, -1).split('%')[0]
        })
        const listenerFu = new Function(FunString)
        const listenerArray = this.field.options.onListener.match(/((\$[^$]+\$))/g).map(i => i.slice(1, -1).split('%')[0])
        const run = (listenKey) => {
          const lstVal = listenerFu.call(this)
          if (lstVal !== void 0) {
            // console.log(`${this.fieldId}#${this.field.options.tableLabel} =>`, lstVal, `from ${this.fieldLib[listenKey].options.label || this.fieldLib[listenKey].options.tableLabel}#${listenKey}`)
            // console.log(`${this.fieldId}#${this.field.options.tableLabel} =>`, lstVal)
            this.formRow.row[this.fieldId] = lstVal
            this.$forceUpdate()
            // console.log(this.pushFn)
            // if (this.pushFn) this.onPushFnHandler(lstVal)
          }
        }
        if (listenerArray) {
          listenerArray.forEach((listenKey) => {
            if (listenKey.indexOf('table_') === 0) {
              this.$watch(`formRow.row.${listenKey}`, () => run(listenKey), { immediate: true })
            } else {
              this.$watch(`formData.${listenKey}`, () => run(listenKey), { immediate: true })
            }
          })
        }
      }
    },
    // 应对监听事件时序混乱的另一种解决方案
    initPushHandler() {
      if (this.designer.previewStatus) return
      if (!this.field.options.onPush) return
      console.log(`${this.fieldId}#${this.field.options.tableLabel} initPushHandler`)
      let FunString = this.field.options.onPush
      FunString = FunString.replace(/(\$[^$]+\$)/g, (iStr) => {
        let key = 'this.formData'
        if (iStr.indexOf('table_') === 1) key = 'this.formRow.row'
        return `${key}.${iStr.slice(1, -1).split('%')[0]}`
      })
      this.$set(this, 'pushFn', { event: new Function('value', FunString) })
      // this.pushFu = { event: new Function('value', FunString) }
      this.$watch(`formRow.row.${this.fieldId}`, (value) => this.onPushFnHandler(value), { immediate: true })
    },
    // push事件触发器
    onPushFnHandler(value) {
      // console.log(`@push value => ${value} ${this.fieldId}#${this.field.options.tableLabel}`)
      this.pushFn.event.call(this, value)
    },
    // 构建字段验证
    buildFieldRules() {
      if (!this.field.formItemFlag && this.field.options.hidden) return
      if (!this.rules) return
      // console.log('in buildFieldRules', this.rules)
      this.rules.splice(0, this.rules.length)
      if (this.field.options.required) {
        this.rules.push({
          required: true,
          // trigger: ['blur', 'change'],
          trigger: ['blur'], /* 去掉change事件触发校验，change事件触发时formModel数据尚未更新，导致radio/checkbox必填校验出错！！ */
          message: this.field.options.requiredHint || '字段值不可为空',
        })
      }

      if (this.field.options.validation) {
        const vldName = this.field.options.validation
        if (FormValidators[vldName]) {
          this.rules.push({
            validator: FormValidators[vldName],
            trigger: ['blur', 'change'],
            label: this.field.options.label,
            errorMsg: this.field.options.validationHint
          })
        } else {
          this.rules.push({
            validator: FormValidators['regExp'],
            trigger: ['blur', 'change'],
            regExp: vldName,
            label: this.field.options.label,
            errorMsg: this.field.options.validationHint
          })
        }
      }

      if (this.field.options.onValidate) {
        const customFn = (rule, value, callback) => {
          const tmpFunc = new Function('rule', 'value', 'callback', this.field.options.onValidate)
          return tmpFunc.call(this, rule, value, callback)
        }
        this.rules.push({
          validator: customFn,
          trigger: ['blur', 'change'],
          label: this.field.options.label
        })
      }
      // console.log(this.rules)
    },
    // --------------------- 事件处理 begin ------------------//
    // 发送字段数据更新
    emitFieldDataChange(newValue, oldValue) {
      this.$emit('field-value-changed', [newValue, oldValue])
      // Yan-这部分应该会触发其他字段添加了的监听事件
    },
    // 同步 更新值到表单
    syncUpdateFormModel(value) {
      this.formModel[this.fieldId] = value
      this.globalModel.$emit(`${this.fieldId}-changed`, value)
    },
    // 从接口请求选项列表
    async handleOptionItemsAsync() {
      // console.log('handleOptionItemsAsync', this.designer.previewStatus)
      if (this.designer.previewStatus) return
      if (this.field.options.optionItemsAsync) {
        const customFn = new Function('request', this.field.options.optionItemsAsync)
        const OptionItems = await customFn.call(this, request)
        // console.log('handleOptionItemsAsync', OptionItems)
        if (OptionItems) {
          this.$set(this, 'customOptionItems', OptionItems)
        }
      }
    },
    // 触发表单单元onCreated事件
    handleOnCreated() {
      if (this.field.options.onCreated) {
        const customFunc = new Function(this.field.options.onCreated)
        const createValue = customFunc.call(this)
        if (createValue) this.syncUpdateFormModel(createValue)
      }
    },
    // 按钮点击事件
    handleButtonClick() {
      // 设计状态不触发点击事件
      if (this.designer.designState) return

      if (this.field.options.onClick) {
        const changeFn = new Function('value', this.field.options.onClick)
        changeFn.call(this, this.formRow)
      }
    },
  }
}
